package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysMenuSaveOrUpdateRequest;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.entity.SysMenu;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.bo.SysMenuBo;
import com.pine.manager.pineframework.query.SysMenuQuery;
import com.pine.manager.pineframework.trigger.AbstractTriggerTemplateAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 系统菜单表新增或修改数据 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-19
 */
@Component
@Slf4j
public class SysMenuSaveOrUpdateTrigger extends AbstractTriggerTemplateAdapter<SysMenuSaveOrUpdateRequest, Boolean> {

    private boolean isSave;

    private SysMenuBo oldSysMenuBo;

    public SysMenuSaveOrUpdateTrigger() {
        super(TriggerTypeEnum.SYS_MENU_SAVE_OR_UPDATE);
    }

    @Override
    protected void before(TriggerContext<SysMenuSaveOrUpdateRequest> triggerContext) {
        SysMenuSaveOrUpdateRequest request = triggerContext.getTriggerRequest();
        isSave = Objects.isNull(request.getId());

        // 尝试查询旧菜单数据
        SysMenuQuery query = new SysMenuQuery();
        query.setId(request.getId());
        oldSysMenuBo = sysMenuManager.getOne(query);

        // 校验
        if (isSave) {
            checkOnSave();
        } else {
            checkOnUpdate();
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean trigger(TriggerContext<SysMenuSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysMenuSaveOrUpdateRequest request = triggerContext.getTriggerRequest();

        // 转换为业务对象
        SysMenuBo newSysMenuBo = sysMenuConvertor.saveRequestToEntityBo(request);

        // 转换为实体
        SysMenu sysMenu = sysMenuConvertor.entityBoToEntity(newSysMenuBo);

        // 新增
        if (isSave) {
            return sysMenuManager.save(sysMenu);
        }

        // 修改
        return sysMenuManager.updateById(sysMenu);
    }

    private void checkOnSave() {
        // 校验菜单是否重复
        if (Objects.nonNull(oldSysMenuBo)) {
            throw new BusinessException(ExceptionCodeEnum.MENU_EXIST);
        }
    }

    private void checkOnUpdate() {
        // 校验菜单是否存在
        if (Objects.isNull(oldSysMenuBo)) {
            throw new BusinessException(ExceptionCodeEnum.MENU_NOT_EXIST);
        }
    }
}
